package com.helloandroid.activitys

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.TextView
import androidx.activity.viewModels
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.app.model.AppCache
import com.helloandroid.base.BaseActivity
import com.helloandroid.dialogs.BindWxTipDialog
import com.helloandroid.dialogs.LoadingDialog
import com.helloandroid.dialogs.StandDialog
import com.helloandroid.dialogs.TXHelpDialog
import com.helloandroid.models.TxViewModel
import com.helloandroid.tools.*
import com.helloandroid.view.IMovingTextDataSource
import com.helloandroid.view.MovingText
import com.helloandroid.vo.TxInfo
import com.helloandroid.vo.TxItem
import dai.common.util.CommonUtils

class TXActivity : BaseActivity() {

    companion object{
        val TxAmoutLst = intArrayOf(30,50,200,1000,5000,10000)
    }

    lateinit var tvCoin:TextView
    lateinit var tvMoney:TextView
    lateinit var btnTx:Button
    lateinit var tvShow: MovingText

    var isReady : Boolean = false

    private var lstCheckBox:ArrayList<CheckBox> = ArrayList()
    var txInfo:TxInfo? = null

    val model:TxViewModel by viewModels()

    var finished = false

    var bindWxReceiver:BindWxReceiver? = null

    override fun getContentViewResId() = R.layout.activity_tx

    override fun initView() {
        tvCoin = findViewById(R.id.tvCoin)
        tvMoney = findViewById(R.id.tvMoney)
        btnTx = findViewById(R.id.btnTx)
        tvShow = findViewById(R.id.tvShow)
        tvShow.dataSource = IMovingTextDataSource {
            val ranIdx = CommonUtils.randomInt(0,AppCache.FkNames.size-1)
            val name = AppCache.FkNames[ranIdx]
            "恭喜玩家 $name  成功提现${GUtils.randomAwardString()}"
        }

        updateCoinAndMoney()

        findBtn(R.id.ibBack).setOnClickListener { finish() }

        findBtn(R.id.ivBtnRecord).setOnClickListener {gotoTxRecord()}

        // 转入余额
        findBtn(R.id.btnChange).setOnClickListener {chgCoinToMoney()}

        // checkbox
        lstCheckBox.clear()
        val cb1 = findViewById<CheckBox>(R.id.cb_1);
        val cb2 = findViewById<CheckBox>(R.id.cb_2);
        val cb3 = findViewById<CheckBox>(R.id.cb_3);
        val cb4 = findViewById<CheckBox>(R.id.cb_4);
        val cb5 = findViewById<CheckBox>(R.id.cb_5);
        val cb6 = findViewById<CheckBox>(R.id.cb_6);
        lstCheckBox.add(cb1)
        lstCheckBox.add(cb2)
        lstCheckBox.add(cb3)
        lstCheckBox.add(cb4)
        lstCheckBox.add(cb5)
        lstCheckBox.add(cb6)
        lstCheckBox.forEach {
            it.setOnClickListener(checkBoxListener)
        }

        // 规则
        findBtn(R.id.tvBtnHelp).setOnClickListener {
            // 显示规则dialog
            TXHelpDialog(this).show()
        }

        // 提现
        btnTx.setOnClickListener(object: ThrottleClickListener() {
            override fun noDoubleClick(v: View?) {
                tx()
            }
        })

        bindWxReceiver = BindWxReceiver()
        registerReceiver(bindWxReceiver, IntentFilter(AppConfig.Action_User_BindWx))

        SmallNativeAdUtil.showNativeAd(this,findViewById(R.id.nativeView))
    }

    private val checkBoxListener = View.OnClickListener {
        onChecked(it as CheckBox)
    }

    private fun onChecked(cb:CheckBox){
        if (!isReady){
            return
        }
        lstCheckBox.forEach {
            if(it != cb){
                it.isChecked = false
            }
        }
    }

    override fun initData() {
        model.getInfo {success,info->
            isReady = success
            txInfo = info
            if (success){
                // 前5个领取过  就不能再领
                updateUI()
            }
        }
    }

    private fun nextTxCheck(){
        // 提现多少
        var selectIdx = -1
        for (i in lstCheckBox.indices){
            if (lstCheckBox[i].isChecked){
                selectIdx = i
                break
            }
        }

        // 只能按照顺序来点
        var mustIdx = -1
        for (j in lstCheckBox.indices){
            if (lstCheckBox[j].isEnabled){
                mustIdx = j
                break
            }
        }

        if (selectIdx < 0){
            StandDialog(this,"请选择提现金额!").show()
            return
        }

        if (mustIdx != selectIdx){
            when(mustIdx){
                0 -> StandDialog(this,"请先提现0.3元!").show()
                1 -> StandDialog(this,"请先提现0.5元!").show()
                2 -> StandDialog(this,"请先提现2.0元!").show()
                3 -> StandDialog(this,"请先提现 10 元!").show()
                4 -> StandDialog(this,"请先提现 50 元!").show()
            }
            return
        }

        //  判断提现
        //  a.1天只提1次
        // 根据 info
        val todayBegin = MyTimeUtils.getStartDayMs(AppUtil.sysTime)
        val todayEnd = todayBegin + 24 * 3600 * 1000L

        val item = txInfo!!.arr.find { it.timeStamp in todayBegin..todayEnd }
        if (item != null){
            StandDialog(this,"今天已经提现过,请明天再进行提现.").show()
            return
        }

        //  b.金币是否足够
        val fenAmount = TxAmoutLst[selectIdx]
        if (!isMoneyEnough(fenAmount)){
            StandDialog(this,"您可用于兑换金额不足!").show()
            return
        }

        // 进行提现
        realTx(fenAmount)

//        if (AppUtil.serverConfig.txVideo > 0){
//            VideoAdUtil.playVideoAd(this){success->
//                if (success){
//                    Analyse.report(AnalyseKey.Tx_Video)
//                    realTx(fenAmount)
//                }else{
//                    AppUtil.toast("视频还没准备好!")
//                }
//            }
//        }else{
//            //
//            Analyse.report(AnalyseKey.Tx_Free)
//            realTx(fenAmount)
//        }
    }
    private fun tx(){
        if (!isReady){
            AppUtil.toast("获取信息失败!")
            return
        }

        //  检查是否已经绑定微信
        if (AppUtil.user.wx_id.isNullOrEmpty()){
            val dialog = BindWxTipDialog(this)
            dialog.show()
            return
        }

        if (AppUtil.serverConfig.txVideo > 0){
            VideoAdUtil.playVideoAd(this){success->
                if (success){
                    // 进行后面的判断
                    Analyse.report(AnalyseKey.Tx_Video)
                    nextTxCheck()
                }else{
                    AppUtil.toast("视频还没准备好!")
                }
            }
        }else{
            Analyse.report(AnalyseKey.Tx_Free)
            nextTxCheck()
        }
    }

    private fun realTx(fenAmount:Int){
        AppUtil.appViewModel().tx(fenAmount){success->
            MyLog.info("realTx callback executed!")
            MyLog.info("提现结果 success:$success,finished = $finished")
            if (success  && !finished){

                txInfo?.arr?.add(TxItem(fenAmount,AppUtil.sysTime))

                // 刷新UI
                updateUI()
            }
        }
    }

    fun isMoneyEnough(fenAmount:Int):Boolean{
        val userFen = AppUtil.user.money  / 100
        return userFen >= fenAmount
    }

    private fun updateCoinAndMoney(){
        val user = AppUtil.user
        tvCoin.text = "我的金币:${user.coin}"
        tvMoney.text = "￥${GUtils.moneyToReadableString(user.money)}"
    }

//    private fun sendCoinOrMoneyChangedBC(){
//        val intent = Intent()
//        intent.action = AppConfig.Action_CoinOrMoney_Changed
//        sendBroadcast(intent)
//    }

    private fun gotoTxRecord(){
        if (!isReady){
            AppUtil.toast("数据还没准备好!")
            return
        }
        val intent = Intent(this,TXRecordActivity::class.java)
        startActivity(intent)
    }

    private fun chgCoinToMoney(){
        val user = AppUtil.user
        if(user.coin == 0){
            AppUtil.toast("您当前没有金币可以进行兑换!")
            return
        }

        val dialog = LoadingDialog(this,"处理中...")
        dialog.show()

        //
        model.chgMoney{success->
            dialog.dismiss()
            if(success){
                AppUtil.toast("兑换成功!")
                updateCoinAndMoney()
                //sendCoinOrMoneyChangedBC()
            }else{
                AppUtil.toast("兑换失败!")
            }
        }
    }

    private fun updateCheckBoxStates(){
        if (txInfo == null){
            return
        }
        if (txInfo!!.arr.size < 1){
            // 没有提现过
            lstCheckBox.forEach { it.isEnabled = true }
            lstCheckBox[0].isChecked = true
        }else{
            // 有提现过
            var size = txInfo!!.arr.size
            if (size >= 5) size = 5

            // 只有最后一个可以点击
            for (i in 0 until 6){
                lstCheckBox[i].isEnabled = i >= size
            }
            lstCheckBox[size].isChecked = true
        }
    }

    override fun onDestroy() {
        bindWxReceiver?.let {
            unregisterReceiver(it)
        }
        finished = true
        super.onDestroy()
    }

    fun updateUI(){
        MyLog.elog("updateUI called................")
        updateCheckBoxStates()
        updateCoinAndMoney()
    }


    // 监听玩家绑定微信成功
    inner class BindWxReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent != null && intent.action == AppConfig.Action_User_BindWx) {
                // 获取提现信息
                txInfo = null
                isReady = false
                model.getInfo { success, newTxInfo ->
                    isReady = success
                    if (success){
                        txInfo = newTxInfo

                        // 更新UI,更新玩家信息
                        updateUI()
                    }
                }
            }
        }
    }

}